import React, { useState } from 'react';
import { Card, Typography, List, Button, Modal, Input, InputNumber, message, Tag, Space, Table } from 'antd';
import { ShoppingCartOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;
const { TextArea } = Input;

const Step2MaterialsList = () => {
    const [selectedProject, setSelectedProject] = useState({ id: 1, name: "城市花园项目" });
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isCartVisible, setIsCartVisible] = useState(false);
    const [selectedMaterial, setSelectedMaterial] = useState(null);
    const [quantity, setQuantity] = useState(1);
    const [otherFee, setOtherFee] = useState(0);
    const [remark, setRemark] = useState('');
    const [shoppingCart, setShoppingCart] = useState([]);
    const navigate = useNavigate();

    // 模拟数据
    const mockMaterials = [
        {
            id: 1,
            name: '螺丝',
            projectId: 1,
            specification: 'Φ20mm',
            unit_price: 45.5,
            expected_amount: 100,
            purchase_amount: 80,
            expected_cost: 4550,
            unit: '个',
            cost: 3640,
            rate: 0.13,
            remark: '首批采购'
        },
        {
            id: 2,
            name: '钢筋',
            projectId: 1,
            specification: 'HRB400 Φ12mm',
            unit_price: 3800,
            expected_amount: 50,
            purchase_amount: 30,
            expected_cost: 190000,
            unit: '吨',
            cost: 114000,
            rate: 0.13,
            remark: '高强度'
        },
        {
            id: 3,
            name: '钢筋',
            projectId: 1,
            specification: 'HRB400 Φ12mm',
            unit_price: 3800,
            expected_amount: 50,
            purchase_amount: 30,
            expected_cost: 190000,
            unit: '吨',
            cost: 114000,
            rate: 0.13,
            remark: '高强度'
        }
    ];

    const projectMaterials = selectedProject
        ? mockMaterials.filter(m => m.projectId === selectedProject.id)
        : [];

    // 显示添加购物车弹窗
    const showAddToCartModal = (material) => {
        setSelectedMaterial(material);

        // 如果已存在，预填已有值
        const existing = shoppingCart.find(item => item.materialId === material.id);
        if (existing) {
            setQuantity(existing.quantity);
            setOtherFee(existing.otherFee);
            setRemark(existing.remark);
        } else {
            setQuantity(1);
            setOtherFee(0);
            setRemark('');
        }

        setIsModalVisible(true);
    };

    // 隐藏弹窗
    const handleCancel = () => {
        setIsModalVisible(false);
        setSelectedMaterial(null);
    };

    // 添加或更新购物车
    const handleAddToCart = () => {
        if (!selectedMaterial) return;

        setShoppingCart(prevCart => {
            const existingIndex = prevCart.findIndex(
                item => item.materialId === selectedMaterial.id
            );

            const totalPrice = ((selectedMaterial.unit_price * quantity) + otherFee) * (1 + selectedMaterial.rate);

            if (existingIndex >= 0) {
                // 已存在，直接覆盖更新
                const updatedCart = [...prevCart];
                updatedCart[existingIndex] = {
                    ...updatedCart[existingIndex],
                    quantity,
                    otherFee,
                    remark,
                    totalPrice,
                    addedTime: new Date().toLocaleString()
                };
                message.success(`已更新 ${selectedMaterial.name}`);
                return updatedCart;
            } else {
                // 新增
                const cartItem = {
                    id: Date.now(),
                    materialId: selectedMaterial.id,
                    materialName: selectedMaterial.name,
                    specification: selectedMaterial.specification,
                    unit: selectedMaterial.unit,
                    unitPrice: selectedMaterial.unit_price,
                    quantity,
                    otherFee,
                    remark,
                    rate: selectedMaterial.rate,
                    totalPrice,
                    addedTime: new Date().toLocaleString()
                };

                message.success(`已成功将 ${selectedMaterial.name} 添加到购物车`);
                return [...prevCart, cartItem];
            }
        });

        setIsModalVisible(false);
        setSelectedMaterial(null);
    };

    // 查看购物车
    const viewShoppingCart = () => {
        if (shoppingCart.length === 0) {
            message.info('购物车为空');
            return;
        }
        setIsCartVisible(true);
    };

    // 关闭购物车弹窗
    const handleCartCancel = () => {
        setIsCartVisible(false);
    };

    // 从购物车移除物品
    const removeFromCart = (itemId) => {
        setShoppingCart(prevCart => prevCart.filter(item => item.id !== itemId));
        message.success('已从购物车移除');
    };

    // 清空购物车
    const clearCart = () => {
        setShoppingCart([]);
        message.success('购物车已清空');
    };

    // 购物车表格列定义
    const cartColumns = [
        {
            title: '材料名称',
            dataIndex: 'materialName',
            key: 'materialName',
            render: (text, record) => (
                <div>
                    <div>{text}</div>
                    <div style={{ fontSize: '12px', color: '#999' }}>{record.specification}</div>
                </div>
            )
        },
        {
            title: '单价',
            dataIndex: 'unitPrice',
            key: 'unitPrice',
            render: (price) => `¥${price}`
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            render: (quantity, record) => `${quantity} ${record.unit}`
        },
        {
            title: '税率',
            dataIndex: 'rate',
            key: 'rate',
            render: (rate) => `${(rate * 100).toFixed(0)}%`
        },
        {
            title: '其他费用',
            dataIndex: 'otherFee',
            key: 'otherFee',
            render: (fee) => fee > 0 ? `¥${fee}` : '-'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            render: (text) => text || '-'
        },
        {
            title: '总价(含税)',
            dataIndex: 'totalPrice',
            key: 'totalPrice',
            render: (price) => <Tag color="blue">¥{price.toFixed(4)}</Tag>
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Button
                    type="link"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => removeFromCart(record.id)}
                >
                    移除
                </Button>
            )
        }
    ];

    // 计算购物车总价
    const cartTotal = shoppingCart.reduce((total, item) => total + item.totalPrice, 0);

    return (
        <div>
            <Title level={4}>构建材料清单</Title>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <Typography.Paragraph style={{ marginBottom: 0 }}>
                    根据项目需求，创建和管理所需的材料清单。
                </Typography.Paragraph>
                <div>
                    <Button
                        icon={<ShoppingCartOutlined />}
                        style={{ marginRight: 10 }}
                        onClick={viewShoppingCart}
                        disabled={shoppingCart.length === 0}
                    >
                        查看购物车 ({shoppingCart.length})
                    </Button>
                    <Button type="primary" onClick={() => navigate("/materials-list")}>
                        编辑
                    </Button>
                </div>
            </div>

            <div style={{ marginTop: 20 }}>
                <Card title="当前材料清单" style={{ width: '100%' }}>
                    {selectedProject ? (
                        projectMaterials.length > 0 ? (
                            <List
                                dataSource={projectMaterials}
                                renderItem={(item) => (
                                    <List.Item
                                        key={item.id}
                                        actions={[
                                            <Button
                                                type="primary"
                                                size="small"   // 按钮变小
                                                icon={<ShoppingCartOutlined />}
                                                onClick={() => showAddToCartModal(item)}
                                                style={{ display: "flex", alignItems: "center" }}
                                            >
                                                加入购物车
                                            </Button>
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={
                                                <Space wrap size={[4, 4]} style={{ lineHeight: "20px" }}>
                                                    <span style={{ fontSize: 14 }}>{item.name}</span>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="blue">{item.specification}</Tag>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="orange">单价: ¥{item.unit_price}</Tag>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="default">单位: {item.unit}</Tag>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="purple">预算: {item.expected_amount} {item.unit}</Tag>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="cyan">已采购: {item.purchase_amount} {item.unit}</Tag>
                                                    <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="magenta">税率: {(item.rate * 100).toFixed(0)}%</Tag>
                                                    {item.remark && (
                                                        <Tag style={{ margin: 0, padding: "0 6px", lineHeight: "20px" }} color="geekblue">备注: {item.remark}</Tag>
                                                    )}
                                                </Space>
                                            }
                                        />
                                    </List.Item>
                                )}
                            />
                        ) : (
                            <Typography.Paragraph type="secondary">该项目暂无材料清单</Typography.Paragraph>
                        )
                    ) : (
                        <Typography.Paragraph type="secondary">请先选择项目</Typography.Paragraph>
                    )}
                </Card>
            </div>

            {/* 添加购物车弹窗 */}
            <Modal
                title={`添加 ${selectedMaterial?.name} 到购物车`}
                open={isModalVisible}
                onOk={handleAddToCart}
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
            >
                {selectedMaterial && (
                    <div>
                        <div style={{ marginBottom: 16 }}>
                            <strong>材料信息:</strong>
                            <div>{selectedMaterial.name} ({selectedMaterial.specification})</div>
                            <div>单价: ¥{selectedMaterial.unit_price} / {selectedMaterial.unit}</div>
                            <div>税率: {(selectedMaterial.rate * 100).toFixed(0)}%</div>
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label>数量: </label>
                            <InputNumber
                                min={1}
                                value={quantity}
                                onChange={setQuantity}
                                style={{ width: '100%', marginTop: 8 }}
                                addonAfter={selectedMaterial.unit}
                            />
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label>其他费用 (元): </label>
                            <InputNumber
                                min={0}
                                value={otherFee}
                                onChange={setOtherFee}
                                style={{ width: '100%', marginTop: 8 }}
                                precision={2}
                                formatter={value => `¥ ${value}`}
                                parser={value => value.replace('¥ ', '')}
                            />
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label>备注: </label>
                            <TextArea
                                value={remark}
                                onChange={(e) => setRemark(e.target.value)}
                                placeholder="请输入备注信息"
                                style={{ marginTop: 8 }}
                                rows={3}
                            />
                        </div>

                        <div style={{ padding: '10px', background: '#f5f5f5', borderRadius: '4px' }}>
                            <strong>
                                小计(含税): ¥{((selectedMaterial.unit_price * quantity) * (1 + selectedMaterial.rate) + otherFee ).toFixed(4)}
                            </strong>
                        </div>
                    </div>
                )}
            </Modal>

            {/* 购物车弹窗 */}
            <Modal
                title={
                    <Space>
                        <ShoppingCartOutlined />
                        购物车 ({shoppingCart.length} 件商品)
                    </Space>
                }
                open={isCartVisible}
                onCancel={handleCartCancel}
                footer={[
                    <Button key="clear" danger onClick={clearCart}>
                        清空购物车
                    </Button>,
                    <Button key="cancel" onClick={handleCartCancel}>
                        关闭
                    </Button>,
                    <Button key="submit" type="primary">
                        提交采购
                    </Button>
                ]}
                width={900}
            >
                <Table
                    columns={cartColumns}
                    dataSource={shoppingCart}
                    rowKey="id"
                    pagination={false}
                    scroll={{ y: 400 }}
                    summary={() => (
                        <Table.Summary>
                            <Table.Summary.Row>
                                <Table.Summary.Cell index={0} colSpan={6}>
                                    <strong>总计</strong>
                                </Table.Summary.Cell>
                                <Table.Summary.Cell index={1}>
                                    <Tag color="red" style={{ fontSize: '16px' }}>
                                        ¥{cartTotal.toFixed(4)}
                                    </Tag>
                                </Table.Summary.Cell>
                                <Table.Summary.Cell index={2}></Table.Summary.Cell>
                            </Table.Summary.Row>
                        </Table.Summary>
                    )}
                />
            </Modal>
        </div>
    );
};

export default Step2MaterialsList;
